import { _decorator, Component, Node, Collider, ITriggerEvent } from 'cc'
const { ccclass, property } = _decorator

const MY_SCOPED = -90
const ENEMY_SCOPED = 60
@ccclass('Bullet')
export class Bullet extends Component {
  @property
  pierce = false // 子弹穿透
  bulletSpeed = 1 // 子弹移动速度
  offsetX = 0 // 子弹X轴偏移量
  isEnemy = false // 是否是敌人子弹
  hurt = 1 // 子弹伤害

  start() {}

  update(deltaTime: number) {
    this.bulletMove(deltaTime)
  }

  onEnable() {
    // 获取碰撞组件
    const collider = this.getComponent(Collider)
    // 监听开始碰撞
    collider.on('onTriggerEnter', this.onTriggerEnter, this)
  }

  onDisable() {
    const collider = this.getComponent(Collider)
    collider.off('onTriggerEnter', this.onTriggerEnter, this)
  }

  // 碰撞处理
  onTriggerEnter(event: ITriggerEvent) {
    if (this.pierce) return
    this.node.destroy()
  }

  // 子弹移动
  bulletMove(deltaTime: number) {
    if (this.isEnemy) {
      // 敌机发射子弹
      let pos = this.node.position
      let zMove = pos.z + this.bulletSpeed
      let xMove = pos.x + this.offsetX
      this.node.setPosition(xMove, pos.y, zMove)
      if (zMove > ENEMY_SCOPED) {
        this.node.destroy()
      }
    } else {
      // 玩家发射子弹
      let pos = this.node.position
      let zMove = pos.z - this.bulletSpeed
      let xMove = pos.x + this.offsetX
      this.node.setPosition(xMove, pos.y, zMove)
      if (zMove < MY_SCOPED) {
        this.node.destroy()
      }
    }
  }

  set(bulletSpeed: number, offsetX: number, hurt: number = 1, isEnemy: boolean = false) {
    this.bulletSpeed = bulletSpeed
    this.offsetX = offsetX
    this.hurt = hurt
    this.isEnemy = isEnemy
  }
}
